import os
import urllib2
import json
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp import template

class EbaySearchHandler(webapp.RequestHandler):
	def get(self):
		# retrieve arguments suggestions, min price, max price, number of results
		suggestions = self.request.get('suggestions').split(',')
		minprice = float(self.request.get('minprice'))
		maxprice = float(self.request.get('maxprice'))
		nresults = self.request.get('results')
		
		# format the url according to the arguments
		url = "http://svcs.ebay.com/services/search/FindingService/v1"
		url += "?OPERATION-NAME=findItemsByKeywords"
		url += "&SERVICE-VERSION=1.0.0"
		url += "&SECURITY-APPNAME=GreatWhi-a91c-4174-b95d-40284d2c7e75"
		url += "&GLOBAL-ID=EBAY-US"
		url += "&RESPONSE-DATA-FORMAT=JSON"
		url += "&REST-PAYLOAD"
		url += "&keywords="
		for i in range (0,len(suggestions)):
			url += suggestions[i] + "%20"
		url += "&paginationInput.entriesPerPage=" + nresults
		
		# send the HTTP request and get the byte stream result		
		js = urllib2.urlopen(url)
		
		# deserialize the byte stream to a JSON object
		result = json.load(js)
		
		#print json.dumps(result['findItemsByKeywordsResponse'][0]['searchResult'][0], sort_keys=True, indent=4)
		
		print "<table class=\"zebra-stripped\">"
		
		# get the number of results, if any get the list of results
		n = int(result['findItemsByKeywordsResponse'][0]['searchResult'][0]['@count'])
		if n > 0:
			its = result['findItemsByKeywordsResponse'][0]['searchResult'][0]['item']

		# for each result, retrieve its information
		for i in range(0, n):
			price = its[i]['sellingStatus'][0]['currentPrice'][0]
			val = float(price['__value__'])
			
			# check if the price of the article is in the price range
			if val >= minprice and val <= maxprice:
				print "<tr>"
				
				print "<td>"
				print "<a href=\"" + its[i]['viewItemURL'][0] + "\">"
				print "<img src=\"" + its[i]['galleryURL'][0] + "\" />"
				print "</a>"
				print "</td>"
				
				print "<td>"
				print "<a href=\"" + its[i]['viewItemURL'][0] + "\">"
				print its[i]['title'][0]
				print "</a>"
				print "</td>"
				
				print "<td>"
				print price['__value__'] + " " + price['@currencyId']
				print "</td>"
				
				print "</tr>"

		print "</table>"

def main():
	application = webapp.WSGIApplication([('/ebay', EbaySearchHandler)],
                                         debug=True)
	util.run_wsgi_app(application)


if __name__ == '__main__':
	main()
